今天要來介紹一下用於數學運算的函式,sqrt 開根號,以及 square 平方
把輸入 array 的每個元素都取平方根並回傳,完整的語法如下。
np.sqrt(arr, out = None)
arr :代表輸入的 array。out :如果有 out,會將結果儲存在 out 內,此 out 要和 arr 的形狀一樣。import numpy as np
array1 = np.array([1, 4, 9, 16])    # 建立一個 array
out_array = np.zeros(4)             # 建立一個空的 array,大小和 array1 一樣大
print(out_array)                    # 檢查建立的 array
# [0. 0. 0. 0.]
x = np.sqrt(array1, out_array)    # 把 array 內的元素都取平方根並放入 x,以及放入 out_array
print(x)
# 輸出
# [1. 2. 3. 4.]
print(out_array)
# 輸出
# [1. 2. 3. 4.]
若 out 與 arr 的形狀不一樣,就會出現 ValueError
import numpy as np
array1 = np.array([1, 4, 9, 16])
out_array = np.zeros((2, 2))
print(out_array)
x = np.sqrt(array1, out_array)
print(x)
print(out_array)

對負數使用 np.sqrt()
import numpy as np
array1 = np.array([-1, -4, -9, -16])
x = np.sqrt(array1)
print(x)
出現 RuntimeWarning,並回傳 nan(非數值)
對複數使用 np.sqrt()
import numpy as np
array1 = np.array([1j, 4 + 2j , 1j, 3 + 4j])    # 建立一個 array
x = np.sqrt(array1)
print(x)
# 輸出
# [0.70710678+0.70710678j 2.05817103+0.48586827j 1.41421356+1.41421356j 2.+1.j]
若有兩個不同的平方根只會輸出一個。
把輸入 array 的每個元素都取平方並回傳,完整的語法如下。
np.square(arr, out = None)
arr :代表輸入的 array。out :如果有 out,會將結果儲存在 out 內,此 out 要和 arr 的形狀一樣。import numpy as np
array1 = np.array([1, 4, 9, 16])    # 建立一個 array
out_array = np.zeros(4)             # 建立一個空的 array,大小和 array1 一樣大
print(out_array)                    # 檢查建立的 array
# 輸出
# [0. 0. 0. 0.]
x = np.square(array1, out_array)    # 把 array 內的元素都取平方並放入 x,以及放入 out_array
print(x)
# 輸出
# [  1.  16.  81. 256.]
print(out_array)
# 輸出
# [  1.  16.  81. 256.]
若 out 與 arr 的形狀不一樣,就會出現 ValueError:同上面 sqrt
對負數使用 np.square()
import numpy as np
array1 = np.array([-1, -4, -9, -16])
x = np.square(array1)
print(x)
# 輸出
# [  1  16  81 256]
對複數使用 np.square()
import numpy as np
array1 = np.array([1 + 5j, 3 + 6j, -9j, 1j])
x = np.square(array1)
print(x)
# 輸出
# [-24.+10.j -27.+36.j -81. +0.j  -1. +0.j]
待續...